<chat-box>

  <message-box>
    <chat-message each={ (msg, index) in state.messages } key={msg.id} message={msg}>
    </chat-message>
  </message-box>
  <chat-input></chat-input>


  <script>
    export default {
      name: 'message-box',
      version: '0.0.1',
      state: {
        messages: [
          ChatUtil.create({
            from: 'Bot',
            content: 'Hello, Please input something.'
          })
        ]
      },

      onMounted() {
        riots.loadAll(
          ['chat/chat-input.riot', 'chat-input'],
          ['chat/message-box.riot', 'message-box'],
          ['chat/chat-message.riot', 'chat-message']
        ).then(([chatInput, messageBox, chatMessage]) => {
          chatInput.mountIt();
          messageBox.mountIt();
          chatMessage.mountIt();
        });

        console.log('box onMounted');
        const debounceScrollMsgIntoView = _.debounce(this.scrollMsgIntoView, 20);

        bus.on('chat-box:add_message', message => {
          this.update({
            messages: this.state.messages.concat(message)
          })
          debounceScrollMsgIntoView(message.id);
        });
        bus.on('chat-box:update_message', ({
          id,
          message
        }) => {
          let target = _.find(this.state.messages, {
            id
          });
          if (target) {
            target = _.merge(target, message)
            this.update({
              messages: this.state.messages
            })
            debounceScrollMsgIntoView(id);
          }
        });
      },
      scrollMsgIntoView(id) {
        setTimeout(() => {
          const msgDom = this.$(`#msgid-${id}`, this.root);
          if (msgDom) {
            msgDom.scrollIntoView();
          }
        }, 20);
      }
    }
  </script>
  <style>
    chat-box {
      display: flex;
      flex: 1;
      flex-direction: column;
      background: url(./static/img/bg.gif) #f9f9f9 no-repeat center 30%;

    }

    chat-box message-box {
      flex: 1;
    }
  </style>
</chat-box>